<template>
  <div class="ticket-detail-page">
    <a-spin :spinning="loading">
      <div v-if="ticket" class="ticket-detail">
        <!-- 头部 -->
        <div class="ticket-header">
          <a-breadcrumb>
            <a-breadcrumb-item>
              <router-link to="/tickets">Ticket System</router-link>
            </a-breadcrumb-item>
            <a-breadcrumb-item>{{ ticket.ticketNumber }}</a-breadcrumb-item>
          </a-breadcrumb>

          <div class="ticket-title-section">
            <h2>{{ ticket.title }}</h2>
            <div class="ticket-actions">
              <a-dropdown>
                <a-button type="primary">
                  Update Status
                  <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu @click="handleStatusChange">
                    <a-menu-item key="in_progress">In Progress</a-menu-item>
                    <a-menu-item key="pending">Pending</a-menu-item>
                    <a-menu-item key="resolved">Resolved</a-menu-item>
                    <a-menu-item key="closed">Close</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="showEditModal">Edit</a-button>
            </div>
          </div>

          <div class="ticket-meta-bar">
            <a-tag :color="getPriorityColor(ticket.priority)">
              {{ getPriorityLabel(ticket.priority) }}
            </a-tag>
            <a-tag :color="getStatusColor(ticket.status)">
              {{ getStatusLabel(ticket.status) }}
            </a-tag>
            <a-tag>
              <component :is="getTypeIcon(ticket.type)" />
              {{ getTypeLabel(ticket.type) }}
            </a-tag>
            <a-tag v-if="ticket.sla?.isBreached" color="red">
              <ClockCircleOutlined /> SLA Breached
            </a-tag>
            <span class="ticket-number">{{ ticket.ticketNumber }}</span>
          </div>
        </div>

        <div class="ticket-body">
          <!-- 左侧主要内容 -->
          <div class="ticket-main">
            <!-- 描述 -->
            <a-card title="Description" class="detail-card">
              <div v-if="isStructuredDescription(ticket.description)" class="description-content structured">
                <div v-html="renderMarkdown(ticket.description)"></div>
              </div>
              <div v-else class="description-content">
                {{ ticket.description }}
              </div>
            </a-card>

            <!-- Related Alert -->
            <a-card v-if="ticket.alertId" title="Related Alert" class="detail-card">
              <a-alert
                message="This ticket was created from an alert"
                type="info"
                show-icon
                style="margin-bottom: 16px"
              />
              <a-descriptions bordered :column="1">
                <a-descriptions-item label="Alert ID">
                  {{ ticket.alertId }}
                </a-descriptions-item>
                <a-descriptions-item label="Actions">
                  <a-button type="link" @click="viewRelatedAlert">
                    <EyeOutlined /> View Alert Details
                  </a-button>
                </a-descriptions-item>
              </a-descriptions>
            </a-card>

            <!-- AI Analysis -->
            <a-card title="AI Analysis" class="detail-card">
              <template #extra>
                <a-space>
                  <a-tag v-if="analysisStatus === 'completed'" color="success">
                    <CheckCircleOutlined /> Completed
                  </a-tag>
                  <a-tag v-else-if="analysisStatus === 'analyzing'" color="processing">
                    <SyncOutlined spin /> Analyzing
                  </a-tag>
                  <a-button
                    v-if="analysisStatus === 'completed'"
                    type="default"
                    size="small"
                    @click="showSaveToKnowledgeModal"
                  >
                    <SaveOutlined /> Save to Knowledge Base
                  </a-button>
                  <a-button
                    type="primary"
                    size="small"
                    :loading="aiAnalysisLoading"
                    :disabled="analysisStatus === 'analyzing'"
                    @click="handleAIAnalysis"
                  >
                    <BulbOutlined /> {{ analysisStatus === 'completed' ? 'Re-analyze' : 'Analyze with AI' }}
                  </a-button>
                </a-space>
              </template>

              <!-- Analyzing State -->
              <div v-if="analysisStatus === 'analyzing'" class="analyzing-state">
                <a-space direction="vertical" size="large" style="width: 100%">
                  <a-alert
                    message="AI is analyzing..."
                    description="Estimated 10-30 seconds. You can continue browsing, results will display automatically when completed."
                    type="info"
                    show-icon
                  >
                    <template #icon>
                      <SyncOutlined spin />
                    </template>
                  </a-alert>

                  <a-progress
                    :percent="Math.floor(analysisProgress)"
                    :show-info="true"
                    status="active"
                  />

                  <div style="text-align: center; color: #999; font-size: 12px">
                    System is invoking AI engine to analyze ticket content, please wait...
                  </div>
                </a-space>
              </div>

              <!-- Completed State -->
              <div v-else-if="analysisStatus === 'completed' && aiAnalysis" class="ai-analysis-content">
                <a-alert
                  message="AI Analysis Result"
                  type="success"
                  show-icon
                  style="margin-bottom: 16px"
                />
                <div class="analysis-section">
                  <h4><strong>📋 Root Cause</strong></h4>
                  <div v-html="renderMarkdown(aiAnalysis.rootCause || 'N/A')"></div>
                </div>
                <div class="analysis-section">
                  <h4><strong>💡 Solution</strong></h4>
                  <div v-html="renderMarkdown(aiAnalysis.solution || 'N/A')"></div>
                </div>
                <div v-if="aiAnalysis.preventiveMeasures" class="analysis-section">
                  <h4><strong>🛡️ Preventive Measures</strong></h4>
                  <div v-html="renderMarkdown(aiAnalysis.preventiveMeasures)"></div>
                </div>
                <div class="analysis-footer">
                  <a-tag color="blue">
                    <ClockCircleOutlined /> Analyzed {{ aiAnalysis.analyzedAt ? dayjs(aiAnalysis.analyzedAt).fromNow() : 'just now' }}
                  </a-tag>
                </div>
              </div>

              <!-- Failed State -->
              <div v-else-if="analysisStatus === 'failed'" class="failed-state">
                <a-alert
                  message="AI Analysis Failed"
                  description="An error occurred during analysis, please try again later"
                  type="error"
                  show-icon
                />
              </div>

              <!-- Pending State -->
              <a-empty v-else description="Click 'Analyze with AI' to get intelligent analysis suggestions" />
            </a-card>

            <!-- Solution -->
            <a-card v-if="ticket.resolution" title="Solution" class="detail-card">
              <a-descriptions bordered :column="1">
                <a-descriptions-item label="Solution">
                  {{ ticket.resolution.solution }}
                </a-descriptions-item>
                <a-descriptions-item v-if="ticket.resolution.rootCause" label="Root Cause Analysis">
                  {{ ticket.resolution.rootCause }}
                </a-descriptions-item>
                <a-descriptions-item v-if="ticket.resolution.preventiveMeasures" label="Preventive Measures">
                  {{ ticket.resolution.preventiveMeasures }}
                </a-descriptions-item>
                <a-descriptions-item label="Resolution Time">
                  {{ dayjs(ticket.resolution.resolvedAt).format('YYYY-MM-DD HH:mm:ss') }}
                </a-descriptions-item>
              </a-descriptions>
            </a-card>

            <!-- Comments区 -->
            <a-card title="Comments" class="detail-card">
              <a-list
                :data-source="ticket.comments"
                :locale="{ emptyText: 'No comments' }"
              >
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a-comment
                      :author="item.userName"
                      :datetime="dayjs(item.createdAt).fromNow()"
                    >
                      <template #avatar>
                        <a-avatar>{{ item.userName.charAt(0).toUpperCase() }}</a-avatar>
                      </template>
                      <template #content>
                        <div>{{ item.content }}</div>
                        <a-tag v-if="item.isInternal" color="orange" size="small">
                          Internal
                        </a-tag>
                      </template>
                    </a-comment>
                  </a-list-item>
                </template>
              </a-list>

              <a-divider />

              <div class="comment-form">
                <a-textarea
                  v-model:value="commentContent"
                  placeholder="Add comment..."
                  :rows="3"
                  :maxlength="500"
                  show-count
                />
                <div class="comment-actions">
                  <a-checkbox v-model:checked="commentInternal">Internal comment</a-checkbox>
                  <a-button type="primary" :loading="commentLoading" @click="handleAddComment">
                    Submit Comment
                  </a-button>
                </div>
              </div>
            </a-card>

            <!-- Status History -->
            <a-card title="Status History" class="detail-card">
              <a-timeline>
                <a-timeline-item
                  v-for="(history, index) in ticket.statusHistory"
                  :key="index"
                  :color="getStatusColor(history.to)"
                >
                  <p>
                    <strong>{{ history.userName }}</strong> changed status from
                    <a-tag size="small">{{ getStatusLabel(history.from) }}</a-tag>
                    to
                    <a-tag size="small">{{ getStatusLabel(history.to) }}</a-tag>
                  </p>
                  <p v-if="history.reason" class="history-reason">Reason: {{ history.reason }}</p>
                  <p class="history-time">{{ dayjs(history.changedAt).format('YYYY-MM-DD HH:mm:ss') }}</p>
                </a-timeline-item>
                <a-timeline-item>
                  <p>
                    <strong>{{ ticket.createdBy || 'System' }}</strong> created ticket
                  </p>
                  <p class="history-time">{{ dayjs(ticket.createdAt).format('YYYY-MM-DD HH:mm:ss') }}</p>
                </a-timeline-item>
              </a-timeline>
            </a-card>
          </div>

          <!-- 右侧边栏 -->
          <div class="ticket-sidebar">
            <!-- Basic Info -->
            <a-card title="Basic Info" size="small" class="sidebar-card">
              <a-descriptions :column="1" size="small">
                <a-descriptions-item label="Creator">
                  <a-avatar size="small">{{ (ticket.createdBy || 'S').charAt(0).toUpperCase() }}</a-avatar>
                  <span style="margin-left: 8px">{{ ticket.createdBy || 'System' }}</span>
                </a-descriptions-item>
                <a-descriptions-item label="Assignee">
                  <template v-if="ticket.assignedTo">
                    <a-avatar size="small">{{ ticket.assignedTo.charAt(0).toUpperCase() }}</a-avatar>
                    <span style="margin-left: 8px">{{ ticket.assignedTo }}</span>
                  </template>
                  <span v-else style="color: #999">Unassigned</span>
                </a-descriptions-item>
                <a-descriptions-item label="Created">
                  {{ dayjs(ticket.createdAt).format('YYYY-MM-DD HH:mm') }}
                </a-descriptions-item>
                <a-descriptions-item label="Updated">
                  {{ dayjs(ticket.updatedAt).fromNow() }}
                </a-descriptions-item>
              </a-descriptions>
            </a-card>

            <!-- SLA -->
            <a-card v-if="ticket.sla" title="SLA" size="small" class="sidebar-card">
              <a-descriptions :column="1" size="small">
                <a-descriptions-item label="Response Deadline">
                  <div :style="{ color: isOverdue(ticket.sla.responseDeadline) ? '#ff4d4f' : '' }">
                    {{ dayjs(ticket.sla.responseDeadline).format('YYYY-MM-DD HH:mm') }}
                  </div>
                </a-descriptions-item>
                <a-descriptions-item label="Resolution Deadline">
                  <div :style="{ color: isOverdue(ticket.sla.resolutionDeadline) ? '#ff4d4f' : '' }">
                    {{ dayjs(ticket.sla.resolutionDeadline).format('YYYY-MM-DD HH:mm') }}
                  </div>
                </a-descriptions-item>
                <a-descriptions-item label="SLA Status">
                  <a-tag :color="ticket.sla.isBreached ? 'red' : 'green'">
                    {{ ticket.sla.isBreached ? 'Breached' : 'Normal' }}
                  </a-tag>
                </a-descriptions-item>
              </a-descriptions>
            </a-card>

            <!-- Tags -->
            <a-card title="Tags" size="small" class="sidebar-card">
              <template v-if="ticket.tags && ticket.tags.length > 0">
                <a-tag v-for="tag in ticket.tags" :key="tag" style="margin-bottom: 8px">
                  {{ tag }}
                </a-tag>
              </template>
              <div v-else style="color: #999">No tags</div>
            </a-card>

            <!-- Related Alert -->
            <a-card v-if="ticket.alertId" title="Related Alert" size="small" class="sidebar-card">
              <router-link :to="`/alerts/${ticket.alertId}`">
                View Alert Details <RightOutlined />
              </router-link>
            </a-card>
          </div>
        </div>
      </div>

      <a-empty v-else description="Ticket not found" />
    </a-spin>

    <!-- Save to Knowledge Base Modal -->
    <a-modal
      v-model:open="saveKnowledgeModalVisible"
      title="Save to Knowledge Base"
      @ok="handleSaveToKnowledge"
      @cancel="saveKnowledgeModalVisible = false"
      :confirmLoading="saveKnowledgeLoading"
      okText="Save"
      cancelText="Cancel"
      width="800px"
    >
      <a-form :model="knowledgeForm" layout="vertical">
        <a-form-item label="Title" required>
          <a-input v-model:value="knowledgeForm.title" placeholder="Enter knowledge base title" />
        </a-form-item>
        <a-form-item label="Category" required>
          <a-select v-model:value="knowledgeForm.category" placeholder="Select category">
            <a-select-option value="Incident Resolution">Incident Resolution</a-select-option>
            <a-select-option value="Performance">Performance</a-select-option>
            <a-select-option value="Security">Security</a-select-option>
            <a-select-option value="Container Orchestration">Container Orchestration</a-select-option>
            <a-select-option value="Caching">Caching</a-select-option>
            <a-select-option value="Database">Database</a-select-option>
            <a-select-option value="Networking">Networking</a-select-option>
            <a-select-option value="Configuration">Configuration</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="Tags">
          <a-select
            v-model:value="knowledgeForm.tags"
            mode="tags"
            placeholder="Add tags (press enter to add)"
            :options="[]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  DownOutlined,
  ClockCircleOutlined,
  RightOutlined,
  BugOutlined,
  BellOutlined,
  ToolOutlined,
  FileAddOutlined,
  BulbOutlined,
  EyeOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  SaveOutlined,
} from '@ant-design/icons-vue'
import { useTicketStore } from '@/stores/ticketStore'
import type { Ticket } from '@/api/ticket'

const route = useRoute()
const router = useRouter()
const ticketStore = useTicketStore()

const loading = ref(false)
const ticket = ref<Ticket | null>(null)
const commentContent = ref('')
const commentInternal = ref(false)
const commentLoading = ref(false)
const aiAnalysisLoading = ref(false)
const aiAnalysis = ref<any>(null)
const analysisStatus = ref<'pending' | 'analyzing' | 'completed' | 'failed'>('pending')
const pollingInterval = ref<number | null>(null)
const progressTimer = ref<number | null>(null)
const analysisProgress = ref(0)
const saveKnowledgeModalVisible = ref(false)
const saveKnowledgeLoading = ref(false)
const knowledgeForm = ref({
  title: '',
  category: '',
  tags: [] as string[]
})

const getPriorityColor = (priority: string) => {
  const colors: Record<string, string> = {
    critical: 'red',
    high: 'orange',
    medium: 'blue',
    low: 'default',
  }
  return colors[priority] || 'default'
}

const getPriorityLabel = (priority: string) => {
  const labels: Record<string, string> = {
    critical: 'Critical',
    high: 'High',
    medium: 'Medium',
    low: 'Low',
  }
  return labels[priority] || priority
}

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    open: 'blue',
    in_progress: 'orange',
    pending: 'gold',
    resolved: 'green',
    closed: 'default',
  }
  return colors[status] || 'default'
}

const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    open: 'Open',
    in_progress: 'In Progress',
    pending: 'Pending',
    resolved: 'Resolved',
    closed: 'Closed',
  }
  return labels[status] || status
}

const getTypeIcon = (type: string) => {
  const icons: Record<string, any> = {
    incident: BugOutlined,
    alert: BellOutlined,
    maintenance: ToolOutlined,
    request: FileAddOutlined,
  }
  return icons[type] || BugOutlined
}

const getTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    incident: 'Incident',
    alert: 'Alert',
    maintenance: 'Maintenance',
    request: 'Request',
  }
  return labels[type] || type
}

const isOverdue = (deadline: string) => {
  return dayjs(deadline).isBefore(dayjs())
}

const isStructuredDescription = (desc: string) => {
  return desc && desc.includes('**Alert Details**')
}

const renderMarkdown = (text: string) => {
  if (!text) return ''

  // Simple markdown renderer
  return text
    // Bold
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    // Headings
    .replace(/^### (.*$)/gim, '<h4>$1</h4>')
    .replace(/^## (.*$)/gim, '<h3>$1</h3>')
    .replace(/^# (.*$)/gim, '<h2>$1</h2>')
    // Line breaks
    .replace(/\n/g, '<br/>')
    // Lists
    .replace(/^- (.*$)/gim, '<li>$1</li>')
    .replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>')
}

const handleStatusChange = async ({ key }: { key: string }) => {
  if (!ticket.value) return

  try {
    loading.value = true
    await ticketStore.updateTicketStatus(ticket.value.id, key as Ticket['status'])
    ticket.value = ticketStore.currentTicket
    message.success('Status updated successfully')
  } catch (error) {
    message.error('Failed to update status')
  } finally {
    loading.value = false
  }
}

const handleAddComment = async () => {
  if (!ticket.value || !commentContent.value.trim()) {
    message.warning('Please enter comment')
    return
  }

  try {
    commentLoading.value = true
    await ticketStore.addComment(ticket.value.id, commentContent.value, commentInternal.value)
    ticket.value = ticketStore.currentTicket
    commentContent.value = ''
    commentInternal.value = false
    message.success('Comment added successfully')
  } catch (error) {
    message.error('Failed to add comment')
  } finally {
    commentLoading.value = false
  }
}

const showEditModal = () => {
  message.info('Edit feature in development...')
}

const viewRelatedAlert = () => {
  if (ticket.value?.alertId) {
    router.push(`/alerts?id=${ticket.value.alertId}`)
    message.info('Navigating to alert details...')
  }
}

const handleAIAnalysis = async () => {
  if (!ticket.value) return

  try {
    aiAnalysisLoading.value = true
    const { default: http } = await import('@/api/http')
    const response = await http.post(`/tickets/${ticket.value.id}/analyze`, {})

    // Backend returns immediate analysis result
    if (response.data) {
      analysisStatus.value = 'completed'
      aiAnalysis.value = {
        rootCause: response.data.rootCause,
        solution: response.data.suggestedActions?.join('\n• ') || 'No solution provided',
        preventiveMeasures: response.data.estimatedResolutionTime ? `预计解决时间: ${response.data.estimatedResolutionTime}\n置信度: ${(response.data.confidence * 100).toFixed(0)}%` : '',
        analyzedAt: new Date().toISOString()
      }
      message.success('AI analysis completed')
    } else if (response.status === 'analyzing') {
      // Start polling
      analysisStatus.value = 'analyzing'
      analysisProgress.value = 0
      startPolling()
      message.info('AI analysis started, please wait...')
    } else if (response.status === 'completed') {
      // Already completed
      analysisStatus.value = 'completed'
      aiAnalysis.value = {
        rootCause: response.rootCause,
        solution: response.solution,
        preventiveMeasures: response.prevention,
        analyzedAt: new Date().toISOString()
      }
      message.success('AI analysis completed')
    }
  } catch (error: any) {
    analysisStatus.value = 'failed'
    message.error(error.message || 'Failed to start analysis')
    console.error('AI analysis error:', error)
  } finally {
    aiAnalysisLoading.value = false
  }
}

const startPolling = () => {
  // Simulate progress
  progressTimer.value = setInterval(() => {
    if (analysisProgress.value < 90) {
      analysisProgress.value += Math.random() * 15
    }
  }, 2000) as unknown as number

  // Poll every 10 seconds
  pollingInterval.value = setInterval(async () => {
    await checkAnalysisStatus()
  }, 10000) as unknown as number

  // Initial check after 3 seconds
  setTimeout(() => checkAnalysisStatus(), 3000)
}

const stopPolling = () => {
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value)
    pollingInterval.value = null
  }
  if (progressTimer.value) {
    clearInterval(progressTimer.value)
    progressTimer.value = null
  }
}

const checkAnalysisStatus = async () => {
  if (!ticket.value) return

  try {
    const { default: http } = await import('@/api/http')
    const response = await http.get(`/tickets/${ticket.value.id}/analysis`)

    if (response.status === 'completed') {
      analysisStatus.value = 'completed'
      analysisProgress.value = 100
      aiAnalysis.value = {
        rootCause: response.rootCause,
        solution: response.solution,
        preventiveMeasures: response.prevention,
        analyzedAt: response.completedAt
      }
      stopPolling()
      message.success('AI analysis completed!', 3)
    } else if (response.status === 'failed') {
      analysisStatus.value = 'failed'
      stopPolling()
      message.error('AI analysis failed: ' + (response.error || 'Unknown error'))
    }
  } catch (error) {
    console.error('Failed to check analysis status:', error)
  }
}

onMounted(async () => {
  const ticketId = route.params.id as string
  if (ticketId) {
    loading.value = true
    try {
      ticket.value = await ticketStore.fetchTicketById(ticketId)

      // Check if there's an ongoing or completed analysis
      await checkAnalysisStatus()
      if (analysisStatus.value === 'analyzing') {
        startPolling()
      }
    } catch (error) {
      message.error('Failed to load ticket')
      router.push('/tickets')
    } finally {
      loading.value = false
    }
  }
})

const showSaveToKnowledgeModal = () => {
  if (!ticket.value) return

  // Pre-fill form with ticket data
  knowledgeForm.value = {
    title: ticket.value.title,
    category: 'Incident Resolution',
    tags: ticket.value.tags || []
  }

  saveKnowledgeModalVisible.value = true
}

const handleSaveToKnowledge = async () => {
  if (!ticket.value || !aiAnalysis.value) {
    message.error('Missing ticket or analysis data')
    return
  }

  if (!knowledgeForm.value.title || !knowledgeForm.value.category) {
    message.error('Please fill in required fields')
    return
  }

  try {
    saveKnowledgeLoading.value = true
    const { default: http } = await import('@/api/http')

    await http.post('/knowledge/from-ticket', {
      ticketId: ticket.value.id,
      title: knowledgeForm.value.title,
      content: ticket.value.description,
      category: knowledgeForm.value.category,
      tags: knowledgeForm.value.tags,
      rootCause: aiAnalysis.value.rootCause,
      solution: aiAnalysis.value.solution,
      prevention: aiAnalysis.value.preventiveMeasures
    })

    message.success('Successfully saved to knowledge base!')
    saveKnowledgeModalVisible.value = false
  } catch (error: any) {
    message.error(error.message || 'Failed to save to knowledge base')
  } finally {
    saveKnowledgeLoading.value = false
  }
}

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped lang="scss">
.ticket-detail-page {
  height: 100%;
  overflow: auto;
  background: #f5f5f5;
}

.ticket-detail {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

.ticket-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
}

.ticket-title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 0;

  h2 {
    margin: 0;
    font-size: 24px;
  }
}

.ticket-actions {
  display: flex;
  gap: 12px;
}

.ticket-meta-bar {
  display: flex;
  align-items: center;
  gap: 12px;

  .ticket-number {
    font-family: 'Courier New', monospace;
    color: #999;
    margin-left: auto;
  }
}

.ticket-body {
  display: grid;
  grid-template-columns: 1fr 360px;
  gap: 24px;
}

.ticket-main {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.detail-card {
  :deep(.ant-card-head) {
    background: #fafafa;
  }
}

.description-content {
  white-space: pre-wrap;
  line-height: 1.8;
}

.comment-form {
  .comment-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
  }
}

.history-reason {
  color: #666;
  margin: 4px 0;
}

.history-time {
  color: #999;
  font-size: 12px;
  margin: 0;
}

.ticket-sidebar {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.sidebar-card {
  :deep(.ant-card-head) {
    background: #fafafa;
    min-height: auto;
    padding: 12px 16px;
  }

  :deep(.ant-card-body) {
    padding: 16px;
  }
}

.ai-analysis-content {
  .analysis-section {
    margin-bottom: 20px;

    h4 {
      color: #1890ff;
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 8px;
    }

    p {
      color: #595959;
      line-height: 1.8;
      margin: 0;
      white-space: pre-wrap;
    }
  }

  .analysis-footer {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
  }
}

@media (max-width: 1200px) {
  .ticket-body {
    grid-template-columns: 1fr;
  }

  .ticket-sidebar {
    order: -1;
  }
}
</style>
